<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
    >
          <!-- <el-form-item label="付款人" prop="payerId">
            <UserSelect
                v-model="queryParams.payerId"
                @node-change="handleUserSelect"
                class="!w-240px"
            />
          </el-form-item> -->
          <el-form-item label="付款编号" prop="billNo">
            <el-input
                v-model="queryParams.payCode"
                placeholder="请输入付款编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="费用类型" prop="expenseType">
            <el-select
                v-model="queryParams.expenseType"
                placeholder="请选择费用类型"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.OA_EXPENSE_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式" prop="payMethod">
            <el-select
                v-model="queryParams.payMethod"
                placeholder="请选择付款方式"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.OA_PAY_METHOD)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
              <el-form-item label="付款日期" prop="payDate">
                <el-date-picker
                    v-model="queryParams.payDate"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    class="!w-220px"
                />
              </el-form-item>

          <el-form-item label="审批结果" prop="status">
            <el-select
                v-model="queryParams.status"
                placeholder="请选择审批结果"
                clearable
                class="!w-240px"
            >
              <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <!-- <el-button plain type="primary" @click="handleCreate()">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button> -->
            </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="付款编号" align="center" prop="payCode" min-width="190" />
    <el-table-column label="申请人" align="center" prop="userName" width="100" />
    <el-table-column label="费用归属部门" align="center" prop="deptName" width="120" />
    <el-table-column label="费用类型" align="center" prop="expenseType" width="100">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_EXPENSE_TYPE" :value="scope.row.expenseType" />
      </template>
    </el-table-column>
    <el-table-column label="费用名称" align="center" prop="expenseName" width="100">
      <template #default="scope">
        <dict-tag :type="scope.row.expenseType" :value="scope.row.expenseName" />
      </template>
    </el-table-column>
    <el-table-column label="付款公司" align="center" prop="payCompany" width="220" />
    <el-table-column label="付款方式" align="center" prop="payMethod" width="100">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.OA_PAY_METHOD" :value="scope.row.payMethod" />
      </template>
    </el-table-column>
    <el-table-column label="收款人全称" align="center" prop="receiverName" width="220" />
    <el-table-column label="付款金额" align="center" prop="payAmount" width="110" />
    <el-table-column label="有无发票" align="center" prop="hasInvoice" width="90">
      <template #default="scope">
        {{scope.row.hasInvoice===1?'有':'无'}}
      </template>
    </el-table-column>
    <el-table-column label="审批结果" align="center" prop="status" width="110">
      <template #default="scope">
        <dict-tag :type="DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS" :value="scope.row.status" />
      </template>
    </el-table-column>
    <el-table-column label="支付状态" align="center" prop="payStatus" width="120">
      <template #default="scope">
        <div class="flex items-center justify-center gap-2">
          <span v-if="scope.row.payStatus === 1">已支付</span>
          <span v-else-if="scope.row.payStatus === 2">已取消</span>
          <span v-else>未支付</span>
          
        </div>
      </template>
    </el-table-column>
    <!-- <el-table-column label="付款人" align="center" prop="payerName" width="100" /> -->
    
    
    
    
    
    
    <el-table-column label="付款日期" align="center" prop="payDate" :formatter="dateFormatter2" width="110" />
    
    
    <!-- <el-table-column label="发票金额" align="center" prop="invoiceAmount" width="110" /> -->
    
    <el-table-column label="备注" align="center" prop="remark" width="200" />
    <el-table-column label="创建者" align="center" prop="creatorName" width="100" />
    <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
    />
    <el-table-column label="操作" align="center" min-width="210" fixed="right">
      <template #default="scope">
        <el-button
            v-hasPermi="['oa:payment:query']"
            link
            type="primary"
            @click="handleDetail(scope.row)"
        >
          详情
        </el-button>
        <!-- <el-button
            v-hasPermi="['oa:payment:query']"
            link
            type="primary"
            @click="handleProcessDetail(scope.row)"
        >
          进度
        </el-button> -->
        <el-button
            v-if="scope.row.payStatus === 0 && scope.row.status === 2"
            v-hasPermi="['oa:payment:update']"
            size="small"
            type="primary"
            @click="handlePay(scope.row)"
          >
            支付
          </el-button>
        <el-button
            v-if="scope.row.payStatus === 0 && scope.row.status === 2"
            v-hasPermi="['oa:payment:update']"
            size="small"
            type="warning"
            @click="handleCancelPay(scope.row)"
          >
            取消支付
          </el-button>
        <el-button
            v-if="scope.row.result === 1"
            v-hasPermi="['oa:payment:create']"
            link
            type="danger"
            @click="cancelProcess(scope.row)"
        >
          取消
        </el-button>
      </template>
    </el-table-column>
  </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <DetailDrawer
    v-model="showDetailDrawer"
    :task-id="currentExpenseId"
    title="付款详情" />



  <ProcessInstanceDetailDrawer
    v-model="showDrawer" :process-instance-id="currentProcessInstanceId" title="流程进度"
    @success="handleDrawerSuccess" />
</template>

<script lang="ts" setup>
  import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
  import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
  import { PaymentApi, PaymentVO } from '@/api/oa/payment'
  import * as ProcessInstanceApi from '@/api/bpm/processInstance'
  import UserSelect from '@/views/system/user/UserSelect.vue'
  import ProcessInstanceDetailDrawer from '@/views/bpm/processInstance/components/ProcessInstanceDetailDrawer.vue'
  import DetailDrawer from '@/views/oa/payment/components/DetailDrawer.vue'
  import { useUserStore } from '@/store/modules/user'
  defineOptions({ name: 'PaymentPayer' })

  const message = useMessage() // 消息弹窗
  const router = useRouter() // 路由
  const { t } = useI18n() // 国际化
  const userStore = useUserStore()
  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const list = ref([]) // 列表的数据
  const queryParams = reactive({
      pageNo: 1,
    pageSize: 10,
    payerId: userStore.getUser.id,
    title: undefined,
    expenseType: undefined,
    payMethod: undefined,
    payDate: [],
    receiverAccount: undefined,
    status: 2,
    payStatus: undefined,
    payCode: undefined,
  })
  const queryFormRef = ref() // 搜索的表单
  const showDetailDrawer = ref(false)
  const currentExpenseId = ref<number | undefined>(undefined)

  const showDrawer = ref(false)
  const currentProcessInstanceId = ref('')


  const handleDrawerSuccess = () => {
    showDrawer.value = false
    getList()
  }

  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
              const data = await PaymentApi.getPaymentPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value.resetFields()
    // 重置后保持当前用户作为付款人
    queryParams.payerId = userStore.getUser.id
    handleQuery()
  }

  /** 添加操作 */
  const handleCreate = () => {
    router.push({ name: 'PaymentCreate' })
  }

  /** 详情操作 */
  const handleDetail = (row: PaymentVO) => {
    currentExpenseId.value = row.id
    showDetailDrawer.value = true
  }

  /** 取消请假操作 */
  const cancelProcess = async (row) => {
    // 二次确认
    const { value } = await ElMessageBox.prompt('请输入取消原因', '取消流程', {
      confirmButtonText: t('common.ok'),
      cancelButtonText: t('common.cancel'),
      inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
      inputErrorMessage: '取消原因不能为空'
    })
    // 发起取消
    await ProcessInstanceApi.cancelProcessInstanceByStartUser(row.id, value)
    message.success('取消成功')
    // 刷新列表
    await getList()
  }
  const handleUserSelect = (val) =>{
    queryParams.payerId = val ? val.id : undefined
    console.log('queryParams.payerId',queryParams.payerId)
  }
  /** 审批进度 */
  const handleProcessDetail = (row) => {
    currentProcessInstanceId.value = row.processInstanceId
    showDrawer.value = true
  }

  /** 支付操作 */
  const handlePay = async (row: PaymentVO) => {
    try {
      await ElMessageBox.confirm('确认要标记为已支付吗？', '支付确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await PaymentApi.updatePayStatus(row.id, 1)
      message.success('支付状态更新成功')
      await getList() // 刷新列表
    } catch (error) {
      if (error !== 'cancel') {
        message.error('支付状态更新失败')
      }
    }
  }

  /** 取消支付操作 */
  const handleCancelPay = async (row: PaymentVO) => {
    try {
      await ElMessageBox.confirm('确认要取消支付吗？', '取消支付确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await PaymentApi.updatePayStatus(row.id, 2)
      message.success('支付状态已取消')
      await getList() // 刷新列表
    } catch (error) {
      if (error !== 'cancel') {
        message.error('取消支付失败')
      }
    }
  }

  // fix: 列表不刷新的问题。
  watch(
      () => router.currentRoute.value,
      () => {
        getList()
      }
  )

  /** 初始化 **/
  onMounted(() => {
    getList()
  })
</script>
